<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>axios 取消请求</title>
</head>

<body>
  <h2>axios 取消请求</h2>
  <button id="btn">提交</button>
  <button id="cancel">取消请求</button>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const instance = axios.create({
        baseURL: "/",
        timeout: 10000
      })

      const oBtn = document.getElementById('btn');
      const oCancel = document.getElementById('cancel');

      //拿到一个取消请求的对象(是一个构造函数)
      const CancelToken = axios.CancelToken;
      let cancel = null;
      oBtn.onclick = async function () {
        try {
          const result = await instance.get("/queryLazy", {
            //在配置对象中配置一个cancelToken的配置项,值是实例化的CancelToken对象
            cancelToken: new CancelToken((c) => {
              // 当请求发送的时候,这个回调函数会被执行,并接受一个参数,这个参数其实就是取消当前请求的函数
              // console.log(c);
              cancel = c;
              //一旦请求被中断,则会交给catch处理这个异常
            })
          })
          console.log(result);
        } catch (e) {
          console.log(e, "出现错误");
        }
      }

      //取消请求点击事件
      oCancel.onclick = function () {
        cancel()
      }
    })
  </script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</body>

</html>